import { reactive, computed } from 'vue';

export const useDialog = (opts: any) => {
  const { onShow: onShowHandler, onSubmit: onSubmitHandler, onCancel: onCancelHandler } = opts;
  const state = reactive({
    contentLoading: false,
    loading: false,
    visible: false
  });

  const onSubmit = async () => {
    let res: any = {};
    if (typeof onSubmitHandler === 'function') res = await onSubmitHandler() || {};
    !res.err && hide();
  };
  const onCancel = async () => {
    let res: any = {};
    if (typeof onCancelHandler === 'function') res = await onCancelHandler() || {};
    !res.err && hide();
  };

  const show = async (...args: any[]) => {
    if (typeof onShowHandler === 'function') await onShowHandler(...args);
    state.visible = true;
  };
  const hide = () => {
    state.visible = false;
  };

  const dialogState = computed(() => {
    return {
      contentLoading: state.contentLoading,
      loading: state.loading,
      modelValue: state.visible
    };
  });
  const dialogEvent = {
    'update:model-value': (val) => state.visible = val,
    submit: onSubmit,
    cancel: onCancel
  };

  return { state, dialogState, dialogEvent, onSubmit, onCancel, show };
};
